import React, { memo, useState } from 'react';
import { Card, Button, Select, DatePicker, Space, Spin, Alert } from 'antd';
import { ReloadOutlined, SearchOutlined } from '@ant-design/icons';
import { useWeatherData, useWeatherStats, useCities } from '../hooks/useWeatherQueries';
import LazyDynamicDataTable from './DynamicDataTable';

const { RangePicker } = DatePicker;
const { Option } = Select;

export const WeatherDataWithQuery: React.FC = memo(() => {
  const [selectedCityId, setSelectedCityId] = useState<string | undefined>();
  const [dateRange, setDateRange] = useState<[any, any] | null>(null);
  const [filters, setFilters] = useState<any>({});

  // React Query hooks
  const { data: weatherData = [], isLoading: weatherLoading, error: weatherError, refetch: refetchWeather } = useWeatherData(filters);
  const { data: stats, isLoading: statsLoading } = useWeatherStats();
  const { data: cities = [], isLoading: citiesLoading } = useCities();

  // 处理筛选查询
  const handleSearch = () => {
    let startDate: string | undefined;
    let endDate: string | undefined;
    
    if (dateRange && dateRange[0] && dateRange[1]) {
      startDate = dateRange[0].format('YYYY-MM-DD');
      endDate = dateRange[1].format('YYYY-MM-DD');
    }
    
    setFilters({
      cityId: selectedCityId,
      startDate,
      endDate
    });
  };

  // 重置筛选条件
  const handleReset = () => {
    setSelectedCityId(undefined);
    setDateRange(null);
    setFilters({});
  };

  const isLoading = weatherLoading || statsLoading || citiesLoading;

  if (weatherError) {
    return (
      <Alert
        message="数据加载失败"
        description={weatherError.message}
        type="error"
        showIcon
        action={
          <Button size="small" danger onClick={() => refetchWeather()}>
            重试
          </Button>
        }
      />
    );
  }

  return (
    <Card 
      title="天气数据管理 (React Query)" 
      extra={
        <Space>
          <Button 
            type="primary" 
            icon={<ReloadOutlined />} 
            onClick={handleReset}
            loading={isLoading}
          >
            重置筛选
          </Button>
          <Button 
            icon={<ReloadOutlined />} 
            onClick={() => refetchWeather()}
            loading={isLoading}
          >
            刷新数据
          </Button>
        </Space>
      }
    >
      {/* 筛选条件 */}
      <Card size="small" style={{ marginBottom: 16 }}>
        <Space wrap>
          <div>
            <label style={{ marginRight: 8 }}>选择城市:</label>
            <Select
              placeholder="请选择城市"
              style={{ width: 200 }}
              value={selectedCityId}
              onChange={setSelectedCityId}
              allowClear
              loading={citiesLoading}
            >
              {cities.map((city: any) => (
                <Option key={city.id} value={city.id}>
                  {city.name} ({city.country})
                </Option>
              ))}
            </Select>
          </div>
          <div>
            <label style={{ marginRight: 8 }}>时间范围:</label>
            <RangePicker
              value={dateRange}
              onChange={setDateRange}
              format="YYYY-MM-DD"
              placeholder={['开始日期', '结束日期']}
            />
          </div>
          <Button 
            type="primary" 
            icon={<SearchOutlined />}
            onClick={handleSearch}
            loading={isLoading}
          >
            查询
          </Button>
        </Space>
      </Card>
      
      {/* 数据统计 */}
      {stats && (
        <Card size="small" style={{ marginBottom: 16 }}>
          <Space>
            <span>总记录数: <strong>{stats.totalWeatherRecords}</strong></span>
            <span>活跃城市: <strong>{stats.activeCities}</strong></span>
            <span>近期记录: <strong>{stats.recentRecords}</strong></span>
          </Space>
        </Card>
      )}
      
      {/* 数据表格 */}
      <Spin spinning={isLoading}>
        <LazyDynamicDataTable
          data={weatherData}
          rowKey="id"
          pagination={{ 
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条数据`
          }}
          loading={weatherLoading}
        />
      </Spin>
    </Card>
  );
});

WeatherDataWithQuery.displayName = 'WeatherDataWithQuery';

export default WeatherDataWithQuery;